//
//  ShipingViewController.m
//  B段项目
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 徐茂怀. All rights reserved.
//

#import "ShipingViewController.h"
#import "XMHNetWorkongMethods.h"
#define POSTURL @"http://api.haodou.com/index.php?appid=2&appkey=9ef269eec4f7a9d07c73952d06b5413f&format=json&sessionid=1446510860323&vc=77&vn=5.4.0&loguid=0&deviceid=haodou99000505722929&uuid=a6afb132369a979ba3427eec69189063&channel=xiaomi_v540&method=Info.getVideoIndexData&virtual=&signmethod=md5&v=2&timestamp=1446521807&nonce=0.5540476473852274&appsign=ee43f17e3c8f395a381ae816403e0d1b"
#import "ShipingHeaderView.h"
#import "FitHeader.h"
#import "UINavigationBar+Awesome.h"
#import "ShipingListTableViewCell.h"
#define NAVBAR_CHANGE_POINT 50
#import "ShipingListDetailViewController.h"
#import "ShipingPlayViewController.h"
#import "SingleTon.h"
@interface ShipingViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong)NSArray *cate_id;
@end

@implementation ShipingViewController

-(void)loadView
{
    [super loadView];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = YES;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -80 * FitHeight, self.view.frame.size.width, self.view.frame.size.height + 20 * FitHeight) style:UITableViewStyleGrouped];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    _tableView.dataSource = self;

    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setTableFooterView:v];
    
    ShipingHeaderView *view = [[ShipingHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 370 * FitHeight)];
    _tableView.tableHeaderView = view;
    [self.view addSubview:_tableView];
   
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _listArray = nil;
        _listArray = [NSMutableArray array];
        NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *path = [str stringByAppendingPathComponent:@"视屏首页"];
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager removeItemAtPath:path error:nil];
        [self getData];
        [self.tableView reloadData];
    }];
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    _progressView.labelText = @"加载中,不要着急";
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_progressView show:YES];
    _progressView.backgroundColor = [UIColor colorWithRed:0.75 green:0.77 blue:0.77 alpha:0.5];
    [self.view addSubview:_progressView];
    [self getData];
}

-(void)getData
{
    NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *path = [str stringByAppendingPathComponent:@"视屏首页"];
    if ([NSDictionary dictionaryWithContentsOfFile:path]) {
        NSDictionary *data = [NSDictionary dictionaryWithContentsOfFile:path];
        NSDictionary *dic = [data objectForKey:@"result"];
        self.listArray = [dic objectForKey:@"index_recommend"];
        [_tableView.header endRefreshing];
        [_progressView removeFromSuperview];
        [self.tableView reloadData];
    }
    else
    {
        [XMHNetWorkongMethods getDataVyString:POSTURL BodyString:[NSDictionary dictionaryWithObjectsAndKeys:@"0",@"offset", nil] WithDataBlock:^(id data) {
            NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
            NSString *path = [str stringByAppendingPathComponent:@"视屏首页"];
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager createFileAtPath:path contents:data attributes:nil];
            NSDictionary *dic = [data objectForKey:@"result"];
            self.listArray = [dic objectForKey:@"index_recommend"];
            [_tableView reloadData];
            [_tableView.header endRefreshing];
            [self.tableView reloadData];
            [_progressView removeFromSuperview];
        } WithFailure:^(NSError *error) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"网络故障" message:@"请检查网络" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                [alertController removeFromParentViewController];
                [_tableView.header endRefreshing];
                [_tableView.footer endRefreshing];
                [_progressView removeFromSuperview];
            }];
            UIAlertAction *going = [UIAlertAction actionWithTitle:@"继续加载" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self getData];
                [alertController removeFromParentViewController];
            }];
            [alertController addAction:going];
            [self presentViewController:alertController animated:YES completion:nil];
            [alertController addAction:ok];
        }];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIColor * color = [UIColor colorWithRed:0.12 green:0.63 blue:0.59 alpha:1];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tableView.delegate = self;
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tableView.delegate = nil;
    [self.navigationController.navigationBar lt_reset];
}

#pragma mark UITableViewDatasource

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [_listArray[section] objectForKey:@"CateName"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_listArray[section]objectForKey:@"list"] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"cell";
    ShipingListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        cell = [[ShipingListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ShipingModel *model = [[ShipingModel alloc]init];
    [model setValuesForKeysWithDictionary:[[_listArray[indexPath.section]objectForKey:@"list"]objectAtIndex:indexPath.row]];
    cell.model = model;
    //cell动画
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 50 * FitHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc]init];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(130 * FitWidth, 5 * FitHeight, 100 * FitWidth, 30 * FitHeight);
    [button setTitle:@"查看更多" forState:0];
    button.titleLabel.font = [UIFont fontWithName:@"Helvetica-LightOblique" size:22 * FitWidth];
    [footerView addSubview:button];
    button.tag = 1000 + section;
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.hidesBottomBarWhenPushed = YES;
    ShipingPlayViewController *playvc = [[ShipingPlayViewController alloc]init];
    NSString *str = [[[_listArray[indexPath.section]objectForKey:@"list"] objectAtIndex:indexPath.row] objectForKey:@"RecipeId"];
    [[SingleTon shareSingleTon]setRid:str];
    [self.navigationController pushViewController:playvc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)buttonAction:(UIButton *)button
{
    NSInteger s = button.tag - 1000;
    ShipingListDetailViewController *vc = [[ShipingListDetailViewController alloc]init];
    vc.cate_id =  [[_listArray[s]objectForKey:@"CateId"]integerValue];
    vc.cateName = [_listArray[s]objectForKey:@"CateName"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100 * FitHeight;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
